package com.im.mr.idongri.log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;

public class WebLogParser {
    public static final String delimit_pure = "|@@|";
    public static final String delimit = "\\|@@\\|";

    static SimpleDateFormat sd1 = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.US);

    static SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static WebLogBean parser(String line) {
        WebLogBean webLogBean = new WebLogBean();
        if (line.indexOf(delimit_pure) > 0) {
            String[] arr = line.split(delimit);
            webLogBean.setRemote_addr(arr[0]);
            webLogBean.setTime_local(parseTime(arr[1].substring(1)));
            webLogBean.setRequest(arr[2]);
            webLogBean.setExe_time(arr[3]);
            webLogBean.setStatus(arr[4]);
            webLogBean.setBody_bytes_sent(arr[5]);
            webLogBean.setHttp_referer(arr[6]);
            webLogBean.setHttp_user_agent(arr[7]);
            webLogBean.setParam(arr[8]);
            if (Integer.parseInt(webLogBean.getStatus()) >= 400
                    ||webLogBean.getBody_bytes_sent().equals("0")) {// 大于400，HTTP错误
                webLogBean.setValid(false);
            }
        }else{
            webLogBean.setValid(false);
        }
        return webLogBean;
    }

    public static String parseTime(String dt) {
        String timeString = "";
        try {
            Date parse = sd1.parse(dt);
            timeString = sd2.format(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return timeString;
    }

    public static void main(String[] args) {
        String line = "100.97.90.71|@@|15/Aug/2017:16:00:05 +0800|@@|POST /api/customer/getDoctorSkillList HTTP/1.0|@@|0.046|@@|200|@@|3750|@@|-|@@|Mozilla/5.0 (Linux; U; Android 4.3; zh-cn; HUAWEI B199 Build/HuaweiB199) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1|@@|terminal=2&versionCode=3915633&mobileType=HUAWEI+B199&systemType=4.3&imeiCode=A0000049ACD171&versionName=3.9.3&channel=dr360&fchanel=x%04ssax%03%06&groupId=8&optionId=0&pageNo=7&pageSize=10";
        WebLogParser wp = new WebLogParser();
        String parseTime = wp.parseTime("18/Sep/2013:06:49:48");
        String[] arr = line.split("\\|@@\\|");
        System.out.println(Arrays.asList(arr));
        System.out.println(parseTime);
    }

}
